package com.dong.controller;

import com.dong.base.BaseController;
import com.dong.config.PropertiesUtil;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class FileController extends BaseController {

    @Autowired
    PropertiesUtil propertiesUtil;

    @RequestMapping(value = "/fileUploadPage")
    public String uploadFilePage() {
        logger.info("test getProperties : fileUploadPath=" + propertiesUtil.getFileUploadPath());
        return "file_upload";
    }

    @RequestMapping(value = "/fileUpload")
    @ResponseBody
    public Object fileUpload(HttpServletRequest request) {
        String successStr = "成功文件：";
        String failedStr = "失败文件：";
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
//                return "false";
                failedStr += file.getOriginalFilename() + ";";
            }
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            logger.info(fileName + "-->" + size);

            String path = propertiesUtil.getFileUploadPath();
            File dest = new File(path + "/" + fileName);
            if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                dest.getParentFile().mkdir();
            }
            try {
                file.transferTo(dest); //保存文件
                successStr += file.getOriginalFilename() + ";";
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                failedStr += file.getOriginalFilename() + ";";
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                failedStr += file.getOriginalFilename() + ";";
            }
        }

        return "上传结果：" + successStr + failedStr;
    }
}